﻿using UnityEngine;
using System.Collections;

public class MobileInput : MonoBehaviour {

    private ITouchable touchHeld = null;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }

        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hitTest;
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitTest))
            {
//                print("Mobile Input detected a hit on " + hitTest.collider.gameObject.name);
                ITouchable touchableObject = TouchableList.Instance.FindTouchable(hitTest.collider.gameObject);

                if (touchableObject != null && touchableObject.TouchEnabled)
                {
                    Vector3 worldTouch = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                    worldTouch.z = touchableObject.GetColliderObject().transform.position.z;
                    touchableObject.OnTouch(Input.mousePosition, worldTouch);
                    if (touchableObject.HoldsTouch())
                    {
                        touchHeld = touchableObject;
                    }
                }
                else
                {
                    print("No object retained");
                    touchHeld = null;
                }

            }
        }

        if (Input.GetMouseButtonUp(0))
        {
            if (touchHeld != null && touchHeld.HoldsTouch())
            {
                Vector3 worldRelease = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                worldRelease.z = touchHeld.GetColliderObject().transform.position.z;
                touchHeld.OnRelease(Input.mousePosition, worldRelease);
                touchHeld = null;
            }
        }

        if (touchHeld != null && touchHeld.HoldsTouch() && Input.GetMouseButton(0))
        {
            Vector3 worldDrag = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            worldDrag.z = touchHeld.GetColliderObject().transform.position.z;
            touchHeld.OnDrag(Input.mousePosition, worldDrag);
        }


	}
}
